<?php

/**
 * Shopalong message stack class
 *
 * Example usage:
 *
 * $messageStack = new MessageStack();
 * $messageStack->add('general', 'Error: Error 1', 'error');
 * $messageStack->add('general', 'Error: Error 2', 'warning');
 *
 * if ($messageStack->getSize('general') > 0)
 * {
 * print_r($messageStack->getMessages('general');
 * }
 *
 * Copyright (c) 2002 osCommerce
 * Portions Copyright (c) 2006 Shopalong
 *
 * Released under the GNU General Public License
 */

class MessageStack
{
	var $_messages;
	
	/**
	 * Constructor function
	 *
	 * @access public
	 */
	
	function MessageStack()
	{
		global $messageToStack, $session;
		
		$this->_messages = array();
		
		if ($session->isRegistered('messageToStack'))
		{
			for ($i=0, $n=sizeof($messageToStack); $i<$n; $i++)
			{
				$this->add($messageToStack[$i]['class'], $messageToStack[$i]['text'], $messageToStack[$i]['type']);
			}
			
			$session->unregister('messageToStack');
		}
	}
	
	/**
	 * Add a message to the stack
	 *
	 * @access public
	 * @param string $class The class of message eg: 'general'
	 * @param string $message The message to be added
	 * @param string $type The type of message (default 'error')
	 */
	
	function add($class, $message, $type='error')
	{
		$this->_messages[] = array(
			'class' => $class,
			'message' => $message,
			'type' => $type
		);
	}
	
	/**
	 * Add a message to the session stack for inclusion in the real stack on the
	 * next page load
	 *
	 * @access public
	 * @param string $class The class of message eg: 'general'
	 * @param string $message The message to be added
	 * @param string $type The type of message (default 'error')
	 */
	
	function addSession($class, $message, $type='error')
	{
		global $messageToStack, $session;
		
		if (!$session->isRegistered('messageToStack'))
		{
			$session->register('messageToStack');
			$messageToStack = array();
		}
		
		$messageToStack[] = array(
			'class' => $class,
			'text' => $message,
			'type' => $type
		);
	}
	
	/**
	 * Reset/clear the stack
	 *
	 * @access public
	 */
	
	function reset()
	{
		$this->_messages = array();
	}
	
	/**
	 * Get the messages for a specified class
	 *
	 * @access public
	 * @param string $class The class of messages to get eg: 'general'
	 */
	
	function getMessages($class)
	{
		$output = array();
		
		for ($i=0, $n=sizeof($this->_messages); $i<$n; $i++)
		{
			if ($this->_messages[$i]['class'] == $class)
			{
				$output[] = $this->_messages[$i];
			}
		}
		
		return $output;
	}
	
	/**
	 * Get the number of messages for a specified class
	 *
	 * @access public
	 * @param string $class The class of messages to get eg: 'general'
	 */
	
	function getSize($class)
	{
		$count = 0;
		
		for ($i=0, $n=sizeof($this->_messages); $i<$n; $i++)
		{
			if ($this->_messages[$i]['class'] == $class)
			{
				$count++;
			}
		}
		
		return $count;
	}
}

?>
